import { useState, useEffect } from 'react';
import { Table, Button, Form, Row, Col, Card, Space, App, Input } from 'antd';
import { getOnlineUserList, forceLogout } from '@/api/login';
import { PoweroffOutlined, SearchOutlined } from '@ant-design/icons';
import AuthControl from '@/components/common/AuthControl';
import hasElementAuth from '@/utils/auth';

const OnlineUserIndex = () => {
  const [form] = Form.useForm();
  const { modal,message } = App.useApp();
  const [searchForm, setSearchForm] = useState({
    label: "",
    size: 10,
    current: 1
  });
  
  const [total, setTotal] = useState(0);
  const [tableData, setTableData] = useState([]);
  const [loading, setLoading] = useState(false);

  const getColumns = () => {
    const baseColumns =[
      {
        title: '用户名',
        dataIndex: 'label',
        key: 'label'
      }
    ]
    if(hasElementAuth(['forceLogout'])){
      baseColumns.push(
        {
          title: '操作',
          key: 'action',
          width: 200,
          render: (_, record) => (
            <Space>
              <Button 
                icon={<PoweroffOutlined />} 
                onClick={() => forceLogoutUser(record.value)} 
                danger
              >
                强制下线
              </Button>
            </Space>
          )
        }
      )
    }
    return baseColumns;
  };

  /**
   * 查询在线用户列表
   */
  const searchOnlineUsers = (formData) => {
    setLoading(true);
    const params = formData || searchForm;
    getOnlineUserList(params)
      .then(res => {
        if (res.data && res.data.others) {
          setTableData(res.data.others);
          setTotal(res.data.total || 0);
        } else {
          setTableData([]);
          setTotal(0);
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  /**
   * 强制用户下线
   */
  const forceLogoutUser = (token) => {
    modal.confirm({
      title: '确定要强制该用户下线吗？',
      content: '此操作将立即终止该用户的会话，请谨慎操作。',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        setLoading(true);
        forceLogout(token)
          .then(() => {
            message.success("用户已被强制下线");
            searchOnlineUsers();
          })
          .finally(() => {
            setLoading(false);
          });
      }
    });
  };

  useEffect(() => {
    searchOnlineUsers();
  }, []);

  const handleTableChange = (pagination) => {
    const formData = {
      ...searchForm,
      current: pagination.current,
      size: pagination.pageSize
    };
    
    // 如果pageSize发生变化，重置到第一页
    if (pagination.pageSize !== searchForm.size) {
      formData.current = 1;
    }
    
    setSearchForm(formData);
    searchOnlineUsers(formData);
  };

  const handleSearch = (values) => {
    const formData = {
      ...searchForm,
      label: values.label || "",
      current: 1 // 重置为第一页
    };
    setSearchForm(formData);
    searchOnlineUsers(formData);
  };

  return (
    <Card>
      <AuthControl permission="search">
        <Form form={form} onFinish={handleSearch}>
          <Row gutter={24}>
            <Col span={8}>
              <Form.Item name="label" label="用户名">
                <Input placeholder="请输入用户名" allowClear/>
              </Form.Item>
            </Col>
            <Col span={16} style={{ textAlign: 'right' }}>
              <Form.Item>
                  <Button type="primary" htmlType="submit" loading={loading} icon={<SearchOutlined />} style={{ marginRight: 8 }}>
                    查询
                  </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </AuthControl>
      <Table 
        columns={getColumns()}
        dataSource={tableData} 
        rowKey="value" 
        loading={loading}
        scroll={{ y: '45vh' }}
        pagination={{
          current: searchForm.current,
          pageSize: searchForm.size,
          total: total,
          showTotal: (total) => `共 ${total} 条数据`,
          showSizeChanger: true,
          pageSizeOptions: ['5','10', '20', '50', '100']
        }}
        onChange={handleTableChange}
      />
    </Card>
  );
};

export default OnlineUserIndex;